<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use app\admin\model\Admin;
use app\admin\model\Role;
use app\admin\model\Student as StudentM;
use think\Config;
use think\captcha\Captcha;
use think\Db;

class  Counselors extends Base
{
    public $roles = array();
    public $zxs_id = array();

    protected $beforeActionList = [
        'myConfigs'  =>  ['only' => 'showres'],
    ];
    //自定义公共配置参数
    public function myConfigs()
    {
        $user = $this->user_info();
        $education_select = Config::get('education_select'); //文化程度select选项
        $status_config = Config::get('resstatus_config'); //资源状态 文本 颜色
        $contract_rate_select = Config::get('contract_rate_select');  //签约率
        
        
        $this->assign([
            'ra'               => $user['ra'],//当前用户的资源管理权限
            "status_config"    => $status_config, //状态配置数组
            'education_select' => $education_select,
            'contract_rate_select'=>$contract_rate_select
        ]);
    }


    public function rol()
    {
        $rs = Role::all();
        foreach ($rs as $v) {
            $this->roles[$v['r_id']] = $v['r_name'];
        }
    }


    public function varlist()
    {
        //查询用户信息
        $user = $this->user_info();
        //查询当前用户的角色的所有下级角色
        // $list = $this->getmyTeam($user['roles_id']);
        $this->rol();
        $list = $this->getMyTeamUser($user['id']);


        $array = array('core' => array('themes' => array('icons' => false), 'data' => $list));
        $json = json_encode($array);
        //查询咨询团队
        $data = array(
            "setting" => $this->getAllSetting(),
            "json" => $json,
        );
        return view("varlist", $data);
    }

    
    //递归查询用户
    public  function  getMyTeamUser($id)
    {
        $roles_id_arr = [6, 7]; //用于规定要查询的角色
        //查询当前的用户
        $u = Admin::where(['id' => $id])->field("id,username,photo,roles_id,pid")->find();
        //查询子集
        $child = Admin::where(['pid' => $u['id']])->where('roles_id', 'in', $roles_id_arr)->field("id,username,photo,roles_id,pid")->select();
        //创建一个新数组
        $array = array();
        //遍历所有子集
        foreach ($child as $k => $v) {
            //再次调用当前方法查询
            $childs = $this->getMyTeamUser($v['id']);
            //判断返回的值是否为空
            if (!empty($childs)) {
                //如果有子集则新数组元素是数组
                $id = $v['id'];
                $href = "'" . url('showres') . "?id={$id}" . "'";  //拼接跳转链接
                $array[$k] =  array(
                    //子集名称
                    'text' => "<img alt='member' class='img-circle' style='float:left;height: 20px;' src='/static/admin/uploads/headphoto/" . $v['photo'] . "'> <span style='float: left;margin-left:5px;line-height: 20px;'> <a class='showRes' id='{$id}' href={$href}>" . $v['username'] . "(" . $this->roles[$v['roles_id']] . ")</a></span>",
                    //子集
                    'children' => $childs
                );
            } else {
                //如果没有子集则数组元素为字符串
                $id = $v['id'];
                $href = "'" . url('showres') . "?id={$id}" . "'";
                $array[$k] = "<img alt='member' class='img-circle' style='float:left;height: 20px;' src='/static/admin/uploads/headphoto/" . $v['photo'] . "'> <span style='float: left;margin-left:5px;line-height: 20px;'> <a class='showRes' id='{$id}' href={$href}>" . $v['username'] . "(" . $this->roles[$v['roles_id']] . ")</a></span>";
            }
        }
        //返回值
        return $array;
    }

    /**
     *@showres: 显示团队成员的资源  
     *@param  [参数]    id    [用户id]
     *@var    [变量]    $roles_id_arr [用于规定要查询的角色,如: [7,6] ]
     *
     *@date: 2019-07-19 10:11:37
     */
    public function showres()
    {
        $id = input('get.id'); //用户id 如果存在将只显示此用户下的资源
        if (empty($id)) $id = "";

        $key = input('get.key'); //搜索关键字
        $key = trim($key);
       
        $user = $this->user_info();  //当前登录用户信息
        $list = $this->getMyTeamUserArr($user['id']); //获取当前用户下的所有咨询顾问和主管
        $this->UserResAll($list); //筛选出当前用户下的所有咨询顾问

        // 根据id查询用户信息
        $u = Admin::where('id', $id)->field("id,username,photo,roles_id,pid")->find();
        $exp = new \think\db\Expression('field(sstatus,2,5,1,0)'); //自定义排序规则

        //搜索条件
        $search = [];
        if (!empty($key)) $search = ["sid|sname|stel|zxr_tel|semai|zxr_name" => ['like', "%" . $key . "%"]];

        //处理生成查询条件
        if ($u['roles_id'] == 7) {  //如果指定id的用户身份为 7(咨询主管)
            $roles_id_arr = [];  //用于规定要查询的角色
            $child = Admin::where(['pid' => $id])->field("id")->select();
            $child = collection($child)->toArray();

            foreach ($child as $vo) { //将当前主管下的 咨询顾问id 遍历并保存到$roles_id_arr中
                $roles_id_arr[] = $vo['id'];
            }
            // 最终的查询条件
            
            $consultant = $roles_id_arr; //要显示的咨询顾问的id

        } else if ($u['roles_id'] == 6) { //如果指定id的用户身份为 7(咨询顾问)
            // 最终的查询条件
            $consultant[] = $u['id'];
            
        } else { // 如果没有指定id 或 id不是 7和6 默认显示当前用户下的所有 
            // 最终的查询条件
            $consultant = $this->zxs_id;
        }
        $sstatusArr = [0, 1, 2, 5]; //要显示的状态
        if (input('?get.start') && input('?get.end')) {
            $start_time = strtotime(input('get.start')) ;
            $end_time = strtotime(input('get.end'))+3600*24;
            $time_between = array('s.create_time'=>['between',"$start_time, $end_time"]);
        } else {
            $time_between = array();
        }

        //查询数据
        $res = StudentM::
        where('sstatus', 'in', $sstatusArr)
        ->where("consultant", 'in', $consultant)
        ->where($search)
        ->where($time_between)
        ->order($exp)
        ->alias('s')
        ->join('admin a', 's.consultant = a.id','left')
        ->join('admin a2', 's.receptionist = a2.id','left')
        ->field('s.*,a.username as zxsname,a2.username as receptionist')
        ->paginate(10);

        //查询所有咨询师 (转移资源时选择咨询师用)
        $zxs = db("admin")->where(array('roles_id' => 6))->where('id', 'in', $this->zxs_id)->select(); //查询咨询师

        $data = array(  //模板数据
            "u"   => $u,    //根据传过来的id查询出的用户信息
            'zxs' => $zxs,
            "res" => $res,  //资源数据
            "oldkey" => $key,  //搜索关键字
            "id"  => $id,   //限定id
        );

        $this->assign($data);
        return  $this->fetch();
    }




    /**
     * getMyTeamUserArr 获取传入id 的所有咨询师或咨询主管
     * @param int $id   用户id
     * @return array    返回查询到的成员 组成的数组
     */
    public  function  getMyTeamUserArr($id)
    {
        $roles_id_arr = [6, 7]; //用于规定要查询的角色
        $u = Admin::where(['id' => $id])->field("id,username,photo,roles_id,pid")->find();

        $child = Admin::where(['pid' => $u['id']])
            ->where('roles_id', 'in', $roles_id_arr)
            ->field("id,username,photo,roles_id,pid")->select();

        foreach ($child as $k => $v) {

            $child[$k]['child'] = $this->getMyTeamUserArr($v['id']);
        }

        return collection($child)->toArray();
    }




    /**
     * transfer         资源转移
     * @return array    返回操作状态
     */
    public function transfer()
    {
        $aims = input('post.aims'); //操作参数 -1 转到资源池 空 转给指定咨询师
        $resid = input('post.resid'); //要转移的资源id
        $logtext = input('post.logtext');  //主要日志的内容
        $user = $this->user_info(); //当前用户信息
        $res = db('student')->where('sid', $resid)->find(); //查询资源数据

        if ($aims == -1) {
            //转回资源池
            $zx_history = explode(',', $res['zx_history']);  //获取咨询历史并转成数组
            $zxs_all =  db('admin')->where(['poststatus' => 1, 'roles_id' => 6])->select();  //咨询师
            foreach ($zxs_all as $k => $vo) {  //判断资源是否为沉默资源
                if (!in_array($vo['id'], $zx_history)) {
                    $return = db('student')->where('sid', $resid)->update(['sstatus' => 4, 'drop_time' => time(), 'consultant' => -1]);
                    break;
                }
                if ($vo == end($zxs_all)) {  //如果资源无法分配给其他咨询师
                    $this->error('当前资源被多次分配,现已无法分配给其他咨询师。无法转回资源池。', '', ['resid' => $resid]);
                    // $return = db('student')->where('sid',$resid)->update(['sstatus'=>0,'consultant'=>-1]);
                }
            }
        } else if (!empty($aims)) {
            //转给其他咨询师
            $zx_history = explode(',', $res['zx_history']);
            if (!in_array($aims, $zx_history)) $zx_history[] = $aims;
            $zx_history = implode(',', $zx_history);

            $return = db('student')->where('sid', $resid)->update(['consultant' => $aims, 'zx_history' => $zx_history]);
        }

        if ($return) {

            $relog =  db('zylog')->insert([
                'consultant' => $res['consultant'],
                'operator' => $user['id'],
                'res_id' => $resid,
                'content' => $logtext,
                'create_time' => time()
            ]);

            if (!$relog) $this->error('转移记录添加失败');
            $this->success('转移操作成功');
        } else {
            $this->error('数据更新失败, 转移没有成功');
        }
    }



    //查找当前登录用户下的所有咨询师id
    public function UserResAll($arr)
    {
        foreach ($arr as $k => $v) {

            if ($v['roles_id'] == 6)
                $this->zxs_id[] = $v['id'];
            $this->UserResAll($v['child']);
        }
        return false;
    }




    /**
     * checkyzm 校验验证码
     *
     * @return array
     */
    public function checkyzm()
    {
        $code = input('post.code');
        $captcha = new Captcha();

        if ($captcha->check($code)) {
            $this->success('验证通过');
        } else {
            $this->error('验证码错误');
        }
    }




    // 显示签约记录
    public function signingshow()
    {
        $user = $this->user_info();  //当前登录用户信息 
        $list = $this->getMyTeamUserArr($user['id']);
        $this->UserResAll($list);
        $logdata = db('enrollrecord')->order('z.create_time desc')
            ->alias('z')
            ->join('student s', 'z.resid = s.sid')
            ->join('admin a', 'z.signing_consultant = a.id')
            ->field('z.*,a.username,s.sname')
            ->where('a.id', 'in', $this->zxs_id)
            ->select();  //转移日志

        $data = array(  //模板数据
            'logdata' => $logdata
        );
        $this->assign($data);
        return  $this->fetch();
    }







}
